<!doctype html>
<html>
<head>
<style>
	body {width:400px; height:400px; font-family:sans-serif; font-size:.8em; display:none;}
	a {color: #0060BF;}
	
	#chromemilk {float: left; margin-bottom:5px;}
	#options {float: right;}
	
	.clear {clear: both;}
</style>

<script type='text/javascript' src='jquery.js'></script>

<script>
function init() {
	var popup = localStorage.popup || 'igoogle';
	
	if (popup == 'page') {
		// no popup, open rtm page
		openRTMTab();
	}
	else {
		document.body.style.display = 'block';
		
		var frame = document.createElement('iframe');
		frame.setAttribute('width', '100%');
		frame.setAttribute('height', '100%');
		frame.setAttribute('frameborder', '0');
		frame.setAttribute('id', 'rtmframe');
		
		if (popup == 'gmail') {
			// open gmail gadget
			$('body').height(300).width(200);			
			frame.setAttribute('src', 'https://www.rememberthemilk.com/services/modules/gmail/');
		}
		else if (popup == 'iphone') {
			// open iphone web app
			$('body').height(480).width(320);
			frame.setAttribute('src', 'https://i.rememberthemilk.com/');
		}
		else if (popup == 'mobile') {
			// open mobile web app
			$('body').height(300).width(200);
			frame.setAttribute('src', 'https://m.rememberthemilk.com/');
		}
		else { 
			// igoogle and default
			$('body').height(400).width(400);
			frame.setAttribute('src', 'https://www.rememberthemilk.com/services/modules/googleig/');
		}
		
		document.body.appendChild(frame);
	}
	
	chrome.extension.getBackgroundPage().scheduleRequest();
}

function openOptions() {
	var optionsUrl = chrome.extension.getURL('options.html');
	chrome.tabs.create({url: optionsUrl});
}

function openRTMTab() {
	getRTMTab(function(tab) { 
		if (tab) { 
			// Try to reuse an existing RTM tab 
			chrome.tabs.update(tab.id, {selected: true}); 
		} 
		else { 
			chrome.tabs.create({url: "http://www.rememberthemilk.com"}); 
		} 
		// Either way, we don't need the popup anymore 
		window.close();
	});
}

function getRTMTab(callback) {
	var RTM_URL_RE_ = /https?\:\/\/www.rememberthemilk.com\//i; 

	chrome.tabs.getAllInWindow(undefined, function(tabs) { 
		for (var i = 0, tab; tab = tabs[i]; i++) { 
			if (tab.url && RTM_URL_RE_.test(tab.url)) { 
				console.log("found RTM tab");
				callback(tab);
				return; 
			} 
		} 
		console.log("no tab found, opening new tab");
		callback(null); 
	}); 
}
</script>

</head>
<body id='body' onload='init()'>
<div id='chromemilk'><strong>ChromeMilk</strong></div>
<div id='options'>
	<a href='javascript:openOptions()' title='Open options'><img src='img/options.png' alt='Options' /></a>
	<a href='javascript:openRTMTab()' title='Open RTM in new tab'><img src='img/external.png' alt='Open RTM' /></a>
</div>

<br class='clear' />
</body>